import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { inject, observer } from 'mobx-react'
import axios from 'axios'
//import ReactQuill, { Quill, Mixin, Toolbar } from 'react-quill'
import ReactQuill, { Quill } from 'react-quill'
import ImageDrop from './QuillImageDrop.js'
import {Button, Table, Modal, message, Spin} from 'antd'
Quill.register('modules/imageDrop', ImageDrop);

@inject('userStore', 'store')@observer
class UserList extends Component {
  constructor(props) {
    super(props)
    this.state = {
      currentModule: {},
      moduleVisible: false,
      html: ''
    }
  }

  componentDidMount () {
    this.props.userStore.getModuleList();
  }

  //编辑模块弹窗
  handleUpdataModule = (module) => {
    const { getModuleMessage, moduleMessage } = this.props.userStore;
    getModuleMessage({
      moduleId: module.moduleId
    })
    this.setState({
      moduleVisible: true,
      currentModule: module
    })
  }

  //取消编辑模块
  handleCancel = () => {
    this.setState({
      moduleVisible: false,
      currentModule: {}
    })
    this.props.userStore.clearModuleMessage();
  }

  //新增、编辑角色确认
  handleCreateConfirm = () => {
    const _this = this;
    Modal.confirm({
      title: `确认保存当前修改？`,
      onOk() {
        return _this.handleCreate()
      },
      onCancel() {},
    });
  }

  handleConvertBase64UrlToBlob = (urlData) => {
    //去掉url的头，并转换为byte
    const bytes = window.atob(urlData.split(',')[1]);
    //处理异常,将ascii码小于0的转换为大于0
    const ab = new ArrayBuffer(bytes.length);
    const ia = new Uint8Array(ab);
    ia.forEach((i, index) => {
      ia[index] = bytes.charCodeAt(index);
    });
    return new Blob([ia], { type: urlData.split(',')[0].split(':')[1].split(';')[0] });
  };

  //编辑模块
  handleCreate = () => {
    const { saveModuleMessage, rtbImageUpload, moduleListLoading } = this.props.userStore;
    const { currentModule } = this.state;
    const editor = this.refs.reactQuillRef.getEditor();
    let _this = this, promisArr = [], index = 1;
    let delta = editor.getContents();
    delta.ops.forEach(item => {
      if(item.insert.image && item.insert.image.indexOf('http:') < 0) {
        const _index = index;
        const hide = message.loading(`正在上传第 ${_index} 张图片`, 0);
        promisArr.push(Promise.resolve(
          rtbImageUpload(this.handleConvertBase64UrlToBlob(item.insert.image)).then(res => {
            hide();
            if(res.status === 200) {
              item.insert.image = res.data[0].url;
              editor.setContents(delta);
              message.success(`第 ${_index} 张图片上传成功`);
            } else {
              message.error(`第 ${_index} 张图片上传出错`);
            }
            return res;
          }).catch(e => {
            message.error(`第 ${_index} 张图片上传出错`);
            return e;
          }))
        )
        index ++;
      }
    })
    return Promise.all(promisArr).then(values => {
      saveModuleMessage({
        moduleId: currentModule.moduleId,
        messages: editor.container.firstChild.innerHTML
      }).then( res=> {
        if(res.status === 200) {
          _this.handleCancel ();
          message.success('操作成功');
        } else {
          Modal.error({
            title: res.err
          })
        }
      })
    }).catch(e=> {
      console.log(e);
    })
  }

  render() {
    const {moduleList, moduleMessage, moduleListLoading, moduleMessageLoading} = this.props.userStore;
    const columns = [{
      title: '模块ID',
      dataIndex: 'moduleId',
      key: 'moduleId',
      width: 200
    },{
      title: '模块名称',
      dataIndex: 'moduleName',
      key: 'moduleName',
      width: 200
    }, {
      title: '路由地址',
      dataIndex: 'url',
      key: 'url',
      width: 200
    }, {
      title: '操作',
      key: 'action',
      render: (text, record) =>
         <div>
           <a style={{marginRight: 10}} onClick={() => this.handleUpdataModule(record)}>编辑</a>
         </div>
    }];
    const toolbarOptions =  [
      ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
      //['blockquote', 'code-block'],
      [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
      //[{ 'header': 1 }, { 'header': 2 }],               // custom button values
      [{ 'list': 'ordered'}, { 'list': 'bullet' }],
      //[{ 'script': 'sub'}, { 'script': 'super' }],      // superscript/subscript
      [{ 'indent': '-1'}, { 'indent': '+1' }, { 'align': [] }],          // outdent/indent
      //[{ 'direction': 'rtl' }],                         // text direction
      [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
      [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
      //[{ 'font': [] }],
      ['link', 'image'],
      //['clean']                                         // remove formatting button
    ];
    return (
      <div>
        {this.props.store.collapse ?
            <h2 style={{marginBottom: 16}}>
              <Link to="/user/module">模块管理</Link>
            </h2> : null
        }
        <Table pagination={false}
               columns={columns}
               loading={moduleListLoading}
               dataSource={moduleList.slice()} />
        <Modal width={'95%'} maskClosable={false}
               title={`${this.state.currentModule.moduleName}`}
               visible={this.state.moduleVisible}
               okText='保存'
               onOk={() => this.handleCreateConfirm()}
               onCancel={() => this.handleCancel()}>
          <Spin spinning={moduleMessageLoading}>
            <ReactQuill style={{height: 450}}
                        ref='reactQuillRef'
                        modules={{toolbar: toolbarOptions, imageDrop: true}}
                        value={moduleMessage}/>
            <div style={{height: 50}}></div>
          </Spin>
        </Modal>
      </div>
    )
  }
}

export default UserList
